﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lipcas.Common.Extensions;

namespace Douban.Api.Authorization
{
    public class QueryParameterCollection : List<QueryParameter>
    {
        public void Add(string name, string value)
        {
            Add(new QueryParameter(name, value));
        }

        public void Add(QueryParameterCollection otherCollection)
        {
            foreach(var item in otherCollection)
            {
                Add(item);
            }
        }

        public string Get(string name)
        {
            QueryParameter pam = this.SingleOrDefault(p => p.Name == name);
            return pam == null ? null : pam.Value;
        }

        public bool Has(string name)
        {
            QueryParameter pam = this.SingleOrDefault(p => p.Name == name);
            return pam != null;
        }

        public override string ToString()
        {
            return ToString("&");
        }

        public string ToString(string seperator)
        {
            StringBuilder builder = new StringBuilder();

            this.ForEachWithIndex(
                (p, index) =>
                {
                    builder.Append(p);
                    if (index < this.Count - 1) builder.Append(seperator);
                });

            return builder.ToString();
        }

        public static QueryParameterCollection Resolve(string queryString)
        {
            return Resolve(queryString, "&");
        }

        public static QueryParameterCollection Resolve(string queryString, string seperator, bool trim = false)
        {
            QueryParameterCollection collection = new QueryParameterCollection();
            int index = queryString.IndexOf("?");

            if (index >= 0 && index <= 3)
                queryString = queryString.Substring(index + 1);

            string[] queries = queryString.Split(
                new string[] { seperator }, queryString.Length, StringSplitOptions.RemoveEmptyEntries);

            queries.ForEach(query =>
            {
                if (trim) query = query.Trim();
                collection.Add(
                    new QueryParameter(
                        query.Trim().Split(new char[] {'='}, 2)));
            });

            return collection;
        }
    }
}
